package com.lp.security.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lp.common.wechat.WechatService;
import com.lp.common.wechat.mapper.WechatMapper;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.refund.RefundService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static com.lp.common.constant.CommonConstant.WECHAT;

/**
 * @program: backend
 * @description:
 * @author: Ke.Song
 * @since: 2024-05-26 11:11:37
 */
@Configuration
public class WxPayConfig {

    @Autowired
    private WechatMapper wechatMapper;

    private RSAAutoCertificateConfig rsaAutoCertificateConfig;

    private void initWechat() {
        WECHAT = wechatMapper.selectOne(new QueryWrapper<>());
        WechatService.appId = WECHAT.getAppId();
        WechatService.mchId = WECHAT.getMerchantId();
    }

    @Bean
    public RSAAutoCertificateConfig generateRsaAutoCertificateConfig() {
        if (WECHAT == null) {
            initWechat();
        }
        if (rsaAutoCertificateConfig == null) {
            rsaAutoCertificateConfig = new RSAAutoCertificateConfig.Builder()
                    .merchantId(WECHAT.getMerchantId())
                    .privateKey(WECHAT.getPrivateKey())
                    .merchantSerialNumber(WECHAT.getMerchantSerialNumber())
                    .apiV3Key(WECHAT.getApiKey())
                    .build();
        }
        return rsaAutoCertificateConfig;
    }

    @Bean
    public JsapiServiceExtension generatePayConfigJsapiServiceExtension() {
        return new JsapiServiceExtension.Builder()
                .config(generateRsaAutoCertificateConfig())
                .build();
    }

    @Bean
    public RefundService generateRefundService() {
        return new RefundService.Builder().config(generateRsaAutoCertificateConfig()).build();
    }
}
